<?php
 
class MongoController extends \Phalcon\Mvc\Controller {
    const LOOP_CNT = 1;
 
    public function indexAction()
    {
        echo 'this is index.<br>';
        echo '<pre>';
        print_r($this -> request -> get());
        echo '</pre>';
    } 
 
    public function queryAction()
    {
        $params = $this -> request -> get();
        if (! array_key_exists('dataid', $params)) {
            echo 'dataid is required.<br>';
            return;
        } 
 
        $conds = array();
        $dataid = $params['dataid'];
        unset($params['dataid']);

        foreach($params as $key => $value) {
            if ($key != '_url') {
                $conds[$key] = $value;
//                $conds[] = array($key => (string)$value);
            } 
        } 
 
        $label = $this -> total -> selectCollection('label_' . $dataid);
        $raw = $this -> total -> selectCollection('raw_' . $dataid);
        // TODO order by
        $res = $label -> find();
        $res -> sort(array('cno' => 1));
 
        echo $label -> getName() . '：' . $res -> count(true) . '/' . $label -> count() . '件<br>';
 
        foreach(iterator_to_array($res) as $doc) {
            echo '<pre>';
            print_r($doc);
            echo '</pre>';
        } 
         

        if (count($conds) > 1) {
            $condtions = array('$and' => $conds);
        } else {
            $condtions = $conds;
        }

        echo '<pre>';
        print_r($condtions);
        echo '</pre>';

        // multi conditions is AND
        // TODO condition,order by,limit
        $res = $raw -> find($conds);
 
        $res -> limit(10);
        $res -> sort(array('no' => 1));
 
        echo $raw -> getName() . ':' . $res -> count(false) . '/' . $raw -> count() . '件<br>';
 
        foreach(iterator_to_array($res) as $doc) {
            echo '<pre>';
            print_r($doc);
            echo '</pre>';
        } 
    } 
 
    public function clearAction()
    {
        $params = $this -> request -> get();
        if (! array_key_exists('dataid', $params)) {
            echo 'dataid is required.<br>';
            return;
        } 
 
        $dataid = $params['dataid'];
 
        $label = $this -> total -> selectCollection('label_' . $dataid);
        $raw = $this -> total -> selectCollection('raw_' . $dataid);
 
        $label -> drop();
        echo "Great, label was cleared successfully!<br>";
 
        $raw -> drop();
        echo "Great, rawdata was cleared successfully!<br>";
 
        $data = Data :: findFirst(
            array("dataid" => $dataid)
            );
 
        if ($data -> delete()) {
            echo "The data was deleted successfully!<br>";
        } else {
            foreach ($data -> getMessages() as $message) {
                echo $message, "\n";
            } 
        } 
    } 
 
    public function importAction()
    { 
        // todo
        $filel = __DIR__ . '/label.csv';
        $filer = __DIR__ . '/rawdata.csv'; 
        // data
        $id = $this -> addData('テスト');
 
        $rawdatatype = $this -> importLabel($filel, $id);
        $this -> importRawdata($filer, $id, $rawdatatype);
    } 
 
    private function addData($name)
    {
        $data = new Data();
        $data -> dataid = Data :: getNextId1('dataid');
        $data -> nm = $name;
 
        $data -> save();
 
        return $data -> dataid;
    } 
 
    private function importLabel($file, $id)
    {
        $data = file_get_contents($file);
        $data = mb_convert_encoding($data, 'UTF-8', 'sjis');
        $temp = tmpfile();
        fwrite($temp, $data);

        $rawdatatype = array();
        
        for ($n = 1;$n <= self :: LOOP_CNT;$n++) {
            rewind($temp);
 
            while (($row = fgetcsv($temp, 0, ",")) !== false) {
                if (!is_numeric($row[0]))
                    continue;
 
                $label = new Labeln();
                $label -> setCollection($id);
 
                $label -> cno = (int)$row[0];
                $label -> cno2 = empty($row[1]) ? null : (int)$row[1];
                $label -> la = $row[2];
                $label -> cd = empty($row[3]) ? null : $row[3];
                $label -> nm = empty($row[4]) ? null : $row[4];
                $label -> nm2 = empty($row[5]) ? null : $row[5];
                $label -> t = empty($row[6]) ? null : $row[6];
 
                $cat = array();
                $i = 8;
                while (!empty($row[$i])) {
                    $cat[] = array('no' => $i-7, 'nm' => $row[$i]);
                    $i++;
                } 
                $label -> cat = $cat;
 
                if ($label -> save()) {
                } else {
                    echo "Umh, We can't store label right now: \n";
                    foreach ($label -> getMessages() as $message) {
                        echo $message, "\n";
                    } 
                } 
                
                if (empty($label -> t)) {
                    $rawdatatype[$label -> cno] = 'int';
/*                } elseif($label -> t == 'SA') {
                    $rawdatatype[$label -> cno] = 'int';
                } elseif($label -> t == 'NU' or $label -> t == 'FA' ) {
                    $rawdatatype[$label -> cno] = 'string';

                } elseif($label -> t == 'MA') {
                    for ($j = $label -> cno; $j <= $label -> cno2; $j++) {
                        $rawdatatype[$j] = 'int';
                    }

*/                } else {
                    $rawdatatype[$label -> cno] = 'string';
                }
                
            } 
        } 
        fclose($temp);
 
        echo 'label_' . $id . ' is imported.<br>';
        
        return $rawdatatype;
    } 
 
 
 //todo SA、MA、NUの回答をint,doubleに変換
    private function importRawdata($file, $id, $datatype)
    {
        $data = file_get_contents($file);
        $data = mb_convert_encoding($data, 'UTF-8', 'sjis');
        $temp = tmpfile();
        fwrite($temp, $data);
 
        for ($n = 1;$n <= self :: LOOP_CNT;$n++) {
            rewind($temp);
 
            $rowno = 1;
            $labels = fgetcsv($temp, 0, ",");
            $colsize = count($labels);
 
            $isnum = false;
 
            while (($row = fgetcsv($temp, 0, ",")) !== false) {
                $raw = new Rawn();
                $raw -> setCollection($id);
 
                if ($rowno == 1 && is_numeric($row[0]))
                    $isnum = true;
 
                for($i = 0; $i < $colsize; $i++) {
/*                    if ($i == 0) {
                        $raw -> $labels[$i] = $isnum ? (int)$row[$i] : $row[$i] ;
                    } else {
                        $raw -> $labels[$i] = $row[$i];
                    } 
*/
                    if($datatype[$i+1] == 'int') {
                        $raw -> $labels[$i] = (int)$row[$i];
                    } else {
                        $raw -> $labels[$i] = $row[$i];
                    }

                } 
 
                if ($raw -> save()) {
                } else {
                    echo "Umh, We can't store rawdata right now: \n";
                    foreach ($raw -> getMessages() as $message) {
                        echo $message, "\n";
                    } 
                } 
 
                $rowno++;
            } 
        } 
 
        fclose($temp);
 
        echo 'raw_' . $id . ' is imported.<br>';
    } 
} 
 